package com.ktsms.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/5/27 下午1:52
 */
public class MybatisUtil {
    private static final SqlSessionFactory sqlSessionFactory;
    /**
     * 获取SqlSession对象
     * @return SqlSession对象
     */
    static {
        try{
            //读取配置文件
            String resource = "mybatis-config.xml";
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
        }catch (IOException e){
            throw new RuntimeException("加载Mybatis配置文件失败", e);
        }
    }

    public static SqlSession getSqlSession(boolean autoCommit) {
        //获取SqlSession对象
        return sqlSessionFactory.openSession(autoCommit); // 是否自动提交事务
    }

    public static void closeSqlSession(SqlSession sqlSession){
        if (sqlSession != null) {
            sqlSession.close(); // 关闭SqlSession
        }
    }
}
